/****************************************************
*	CNumKeyBoard
*
*	1)数値入力用divを用意する
*		・<div id="NumKeyBoardID"></div>
*
*	2)メンバ変数でCNumKeyBoardをnewする
*		・var cls = new CNumKeyBoard();
*
*	3)onloadでinit(1で用意した数値入力用divのid)を呼び出す
*		・cls.init("NumKeyBoardID");
*
*	4)onloadで初期設定を行う
*		・設定を行わなかった場合は初期値が適応される。
*		・設定内容について。
*			cls.borderStyle				= "solid";				//囲い枠のスタイル[solid]
*			cls.borderColor				= "#00f";				//囲い枠の色[#000]
*			cls.borderWidth				= 3;					//囲い枠の太さ[1]
*			cls.boxBackgroundColor		= "#fff";				//背景色[#fff]
*			cls.boxBalloonHeight		= 8;					//噴出しの長さ[8]
*			cls.boxBalloonWidth			= 8;					//噴出しの太さ[5]
*			cls.boxBalloonOffset		= 10;					//吹き出しの位置[10]
*			cls.textFontColor			= "#555";				//文字色[#000]
*			cls.textFontSize			= 15;					//文字サイズ[20]
*			cls.textBackgroundColor		= "#fff";				//背景色[#fff]
*			cls.buttonFontColor			= "#555";				//ボタン文字色[#000]
*			cls.buttonFontSize			= 15;					//ボタン文字サイズ[20]
*			cls.buttonBackgroundColor	= "#fff";				//ボタン背景色[#ccc]
*			cls.boxX					= 10;					//水平方向の表示位置[20]
*			cls.boxShadowX				= 5;					//影の水平位置（正なら右へ、負なら左へ）[5]
*			cls.boxShadowY				= 5;					//影の垂直位置（正なら右へ、負なら左へ）[5]
*			cls.boxShadowGradate		= 10;					//影のぼかし距離（負の値は不可）[10]
*			cls.boxShadowWidth			= 0;					//影の幅（正なら拡大、負なら縮小）[0]
*			cls.boxShadowColor			= "#999";				//影の色[#999]
*			cls.isParentScroll			= false;				//親エレメントのスクロールした際にボックスを動かすか[false]
*			cls.parentElement			= document.getElementById("mainDiv");	//親エレメント(isParentScrollを使用する場合、または親エレメントがBODYでDIVのスクロールがある場合にセット)[null]
*
*	5)入力エリアを用意する
*		・<input type="text" id="test001" readonly onClick="javaScript:cls.setNumKeyBoard(this, 300);">
*		・idは必須。
*		・onClickでcls.setNumKeyBoardをコールする。
*		・cls.setNumKeyBoardの引数について。
*			第一引数：this
*			第二引数：整数桁数
*			第三引数：小数桁数
*			第四引数：サイン有無(true or false)
*			第五引数：上下切り替えY座標
****************************************************/

/****************************************************
*	update
*
*	2011/10/04 Create
****************************************************/
var strUA			= "";
var Rate			= 1.5;							// フォントの高さに掛けてテーブルの高さにする
var Adj				= 3;							// 補正値

var ParentObj		= null;							// 元の入力エリアの親DIV
var ParentScrX		= 0;							// 親DIVのスクロールX座標
var ParentScrY		= 0;							// 親DIVのスクロールY座標
var TargetObj		= null;							// 元の入力エリア

var BaseObj			= null;							// 当オブジェクトが生成されるDIV
var MeObj			= null;							// 当吹き出し
var MePosX			= 0;							// 吹き出しX座標
var MePosY			= 0;							// 吹き出しY座標
var MeWidth			= 0;							// 吹き出しの幅
var MeHeight		= 0;							// 吹き出しの高さ
var MeCloseFlg		= false;						// 吹き出し非表示フラグ（trueで非表示）

var IntLen			= 10;							// 整数部桁数
var DecLen			= 2;							// 小数部桁数（0以下の場合ポイント入力非表示）
var SignFlg			= true;							// 正負有無フラグ
var SwitchPos		= -1;							// 吹き出しの上下出力切り替え位置

var CNumKeyBoard = function() {
	strUA						= navigator.userAgent.toLowerCase();

	// デフォルト定義
	this.borderStyle			= "solid";
	this.borderColor			= "#000";
	this.borderWidth			= 1;
	this.boxBackgroundColor		= "#000";
	this.boxBalloonHeight		= 8;
	this.boxBalloonWidth		= 5;
	this.boxBalloonOffset		= 10;
	this.textIntLen				= 10;				// 整数部桁数
	this.textDecLen				= 2;				// 小数部桁数
	this.textSign				= true;				// 正負有無
	this.textFontColor			= "#000";			// 入力値表示フォント色
	this.textFontSize			= 20;				// 入力値表示フォントサイズ
	this.textBackgroundColor	= "#fff";			// 入力値表示背景色
	this.buttonFontColor		= "#000";			// ボタン色
	this.buttonFontSize			= 20;				// ボタンサイズ
	this.buttonBackgroundColor	= "#ccc";			// ボタン背景色
	this.boxX					= 20;
	this.boxY					= 0;
	this.boxShadowX				= 5;
	this.boxShadowY				= 5;
	this.boxShadowGradate		= 10;
	this.boxShadowWidth			= 0;
	this.boxShadowColor			= "#999";
	this.isParentScroll			= false;
	this.parentElement			= null;

	this.clickEventName			= "onClick";		//クリックした時のイベント
	if(strUA.indexOf("ipad") != -1) {
		this.clickEventName		= "onTouchEnd";
	}
	this.init = function(divId){
		BaseObj = document.getElementById(divId);
		try {
			if(strUA.indexOf("msie") != -1) {
				document.attachEvent("onmousedown", NumKeyBoardMouseDownListner, false);
				document.attachEvent("onmouseup", NumKeyBoardHidden, false);
			} else if(strUA.indexOf("ipad") != -1) {
				document.addEventListener("touchstart", NumKeyBoardMouseDownListner, false);
				document.addEventListener("touchend", NumKeyBoardHidden, false);
				Adj  = 4;
			} else {
				document.addEventListener("mousedown", NumKeyBoardMouseDownListner, false);
				document.addEventListener("mouseup", NumKeyBoardHidden, false);
			}
		} catch(e) {
//			alert(e);
		}
	}

	/*
	 *
	 */
	this.setNumKeyBoard = function (){
		
		//ダブルタップ拡大の対応
		//メタタグを増やして（拡大禁止）に上書きを行う
		var meta = document.createElement('meta');
		meta.setAttribute('name', 'viewport');
		meta.setAttribute('content', 'user-scalable=0');
		document.getElementsByTagName('head')[0].appendChild(meta);
		try{
			SwitchPos = -1;
			TargetObj	= this.setNumKeyBoard.arguments[0];
			if(this.setNumKeyBoard.arguments[1] != null) {
				IntLen = this.setNumKeyBoard.arguments[1];
			}
			if(this.setNumKeyBoard.arguments[2] != null) {
				DecLen = this.setNumKeyBoard.arguments[2];
			}
			if(this.setNumKeyBoard.arguments[3] != null) {
				SignFlg = this.setNumKeyBoard.arguments[3];
			}
			if(this.setNumKeyBoard.arguments[4] != null) {
				SwitchPos = this.setNumKeyBoard.arguments[4];
			}
			ParentObj = this.parentElement;

			var iHtml		= "";
			var parent		= TargetObj;

			var textWidth	= "95%";
			if(strUA.indexOf("ipad") != -1) {
				textWidth = "85%";
			}

			// 吹き出し位置の計算（但しY座標は仮）
			MePosX		= this.boxX;
			MePosY		= this.boxY;
			while(1) {
				if(parent.nodeName == "BODY") break;
				if(parent.nodeName != "DIV") {
					MePosX	+= parent.offsetLeft;
					MePosY	+= parent.offsetTop;
				} else {
					MePosX	-= parent.scrollLeft;
					MePosY	-= parent.scrollTop;
				}
				parent = parent.offsetParent;
			}
			var CheckPosY = MePosY;
			if(ParentObj != null){
				CheckPosY -= ParentObj.scrollTop;
			}
			// 吹き出し高の計算
			MeHeight  = (this.textFontSize * Rate + Adj);				//入力値表示エリア分
			MeHeight += ((this.buttonFontSize * Rate + Adj) * 5);		//ボタンエリア分
			MeHeight += (this.borderWidth * 2);
			MeHeight += this.boxBalloonHeight;

			if(SwitchPos == -1) {
				SwitchPos = MeHeight + TargetObj.clientHeight;
			}

			// 吹き出し幅の計算
			var textLength = IntLen;
			if(DecLen > 0) {
				textLength += 1 + DecLen;
			}
			if(this.textSign) {
				textLength += 1;
			}
			MeWidth	        = this.textFontSize   * textLength * 0.9 + 20;	// 入力BOXの幅
			var buttonWidth	= this.buttonFontSize * 7          + 20;	// ボタンの幅
			if(MeWidth < buttonWidth) {
				MeWidth = buttonWidth;
			}

			if(CheckPosY > SwitchPos) {
				MePosY -= MeHeight - 10;
				//上吹き出しのしっぽを作成
				iHtml += "<div id='sboxDivOut' ";
				iHtml += "     style='position: absolute;";
				iHtml += "            top: "           + MePosY + "px;";
				iHtml += "            left: "          + (MePosX + this.boxBalloonOffset) + "px;";
				iHtml += "            border-left: "   + this.boxBalloonWidth  + "px solid " + this.borderColor + ";";
				iHtml += "            border-bottom: " + this.boxBalloonHeight + "px solid transparent;'";
				iHtml += ">";
			} else {
				MePosY += TargetObj.clientHeight;
				//下吹き出しのしっぽを作成
				iHtml += "<div id='sboxDivOut' ";
				iHtml += "     style='position: absolute;";
				iHtml += "            top: "         + MePosY + "px;";
				iHtml += "            left:"         + (MePosX + this.boxBalloonOffset) + "px;";
				iHtml += "            border-left: " + this.boxBalloonWidth  + "px solid " + this.borderColor + ";";
				iHtml += "            border-top: "  + this.boxBalloonHeight + "px solid transparent;'";
				iHtml += ">";
			}

			iHtml += "<div id='sboxDiv' ";
			iHtml += "     style='float: left;";
			iHtml += "            width: " + MeWidth + "px;";
			iHtml += "            margin: 0 0 0 -" + (this.boxBalloonWidth + this.boxBalloonOffset) + "px;";
			iHtml += "            background: "    + this.boxBackgroundColor + ";";
			iHtml += "            border-radius: 5px;";
			iHtml += "            border: "        + this.borderStyle + " "   + this.borderWidth + "px " + this.borderColor + ";";
			iHtml += "            box-shadow: "    + this.boxShadowX  + "px " + this.boxShadowY  + "px " + this.boxShadowGradate + "px " + this.boxShadowWidth + "px " + this.boxShadowColor + ";'";
			iHtml += ">";
			var styleText = " style='width: " + textWidth + "; height: " + (this.textFontSize * Rate) + "px; text-align: right; color:" + this.textFontColor + "; font-size:" + this.textFontSize + "px; background-color: " + this.textBackgroundColor + ";'";
			var styleTR = " style='height: " + (this.buttonFontSize * Rate) + "px;'";
			var styleButton = " style='border: 1px solid; text-align: center; width: 33%; color:" + this.buttonFontColor + "; font-size:" + this.buttonFontSize + "px; background-color: " + this.buttonBackgroundColor + ";cursor: pointer;'";
			var initValue = TargetObj.value;
//			if(initValue.length == 0) {
//				initValue = 0;
//			}
			initValue = 0;						// 初期値は0とする
			iHtml += "<div style='text-align: center;'>";
			iHtml += "  <input id='KeyResult' name='KeyResult' type='text'" + styleText + " value='" + initValue + "' readonly>";
			iHtml += "  <table style='width: 100%;'>";
			iHtml += "    <tr" + styleTR + ">";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(7);'>7</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(8);'>8</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(9);'>9</td>";
			iHtml += "    </tr>";
			iHtml += "    <tr" + styleTR + ">";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(4);'>4</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(5);'>5</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(6);'>6</td>";
			iHtml += "    </tr>";
			iHtml += "    <tr" + styleTR + ">";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(1);'>1</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(2);'>2</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(3);'>3</td>";
			iHtml += "    </tr>";
			iHtml += "    <tr" + styleTR + ">";
			if(SignFlg && DecLen > 0) {
				iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(0);'>0</td>";
				iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressSign();'>+/-</td>";
				iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressDot();'>.</td>";
			} else if(SignFlg && DecLen <= 0) {
				iHtml += "      <td colspan='2'" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(0);'>0</td>";
				iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressSign();'>+/-</td>";
			} else if(!SignFlg && DecLen > 0) {
				iHtml += "      <td colspan='2'" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(0);'>0</td>";
				iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressDot();'>.</td>";
			} else {
				iHtml += "      <td colspan='3'" + styleButton + " "+this.clickEventName+"='NumKeyBoardPress(0);'>0</td>";
			}
			iHtml += "    </tr>";
			iHtml += "    <tr" + styleTR + ">";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressCancel();'>Can</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressAC();'>AC</td>";
			iHtml += "      <td" + styleButton + " "+this.clickEventName+"='NumKeyBoardPressOK();'>OK</td>";
			iHtml += "    </tr>";
			iHtml += "  </table>";
			iHtml += "</div>";
			iHtml +="</div>";
			iHtml +="</div>";
			BaseObj.innerHTML = iHtml;
			BaseObj.style.display = "block";

			MeObj	= document.getElementById("sboxDivOut");
			if(MeObj != null) {
				if(this.isParentScroll && ParentObj != null) {
					ParentScrX	= ParentObj.scrollLeft;
					ParentScrY	= ParentObj.scrollTop;
					try {
						if(strUA.indexOf("msie") != -1) {
							ParentObj.attachEvent("onscroll", NumKeyBoardChaseParentScroll, false);
						}else{
							ParentObj.addEventListener("scroll", NumKeyBoardChaseParentScroll, false);
						}
					} catch(e) {
					}
				}
			}

		} catch(e) {
			alert(e)
		}

	};
}

/*
 * 数値入力
 */
function NumKeyBoardPress(num) {
	var elm = document.getElementById("KeyResult");
	var res = elm.value;
	var res_length = 0;
	if(res.indexOf(".") == -1) {
		//整数部入力
		res_length = res.length;
		if(res.charAt(0) == '-') {
			res_length -= 1;
		}
		if(res_length >= IntLen) return;
		if(num == 0 && parseFloat(res) != 0) {
			elm.value = res + num;
		} else if(num != 0 && parseFloat(res) == 0) {
			elm.value = num;
		} else if(num != 0 && parseFloat(res) != 0) {
			elm.value = res + num;
		}
	} else {
		//小数部入力
		res_length = res.length - res.indexOf(".") - 1;
		if(res_length >= DecLen) return;
		elm.value = res + num;
	}
}

/*
 * ＋/－
 */
function NumKeyBoardPressSign() {
	var elm = document.getElementById("KeyResult");
	var res = elm.value;
	if(res.length > 0 && parseFloat(res) != 0) {
		elm.value = 0 - parseFloat(res);
	}
}

/*
 * 小数点入力
 */
function NumKeyBoardPressDot() {
	var elm = document.getElementById("KeyResult");
	var res = elm.value;
	var max_length = 12;
	if(res.charAt(0) == '-') {
		max_length += 1;
	}
	if(res.length == 0) {
		elm.value = "0.";
	} else {
		if(elm.value.indexOf(".") == -1) {
			elm.value = res + ".";
		}
	}
}

/*
 * キャンセル
 */
function NumKeyBoardPressCancel() {
	MeCloseFlg = true;
	NumKeyBoardHidden();
}

/*
 * クリア
 */
function NumKeyBoardPressAC() {
	var elm = document.getElementById("KeyResult");
	elm.value = "";
}

/*
 * ＯＫ
 */

function NumKeyBoardPressOK() {
	var elm = document.getElementById("KeyResult");

	TargetObj.value = NumKeyBoardNumberInsertComma(elm.value);
	MeCloseFlg = true;
	NumKeyBoardHidden();
	TargetObj.onchange();
}

function NumKeyBoardHidden(){
	if(MeCloseFlg) {
		setTimeout("NumKeyBoardHiddenTmr()",500);
		//ダブルタップ拡大の対応
		//メタタグを増やして（拡大許可）に上書きを行う
		var meta = document.createElement('meta');
		meta.setAttribute('name', 'viewport');
		meta.setAttribute('content', 'user-scalable=1');
		document.getElementsByTagName('head')[0].appendChild(meta);
	}
}

function NumKeyBoardHiddenTmr(){
	try {
		BaseObj.style.display="none";
		MeObj = null;
		MeCloseFlg = false;
	} catch(e) {
	}
}

function NumKeyBoardMouseDownListner(e) {
	var posx = 0;
	var posy = 0;
	if(MeObj != null) {
		if(strUA.indexOf("ipad") != -1) {
			posx = e.touches[0].pageX;
			posy = e.touches[0].pageY;

			if(ParentObj != null) {
				posx -= ParentObj.offsetLeft;
				posx += ParentObj.scrollLeft;
				posy -= ParentObj.offsetTop;
				posy += ParentObj.scrollTop;
			}
			posx -= 20;
		} else {
			posx = e.clientX;
			posy = e.clientY;
			if(ParentObj != null) {
				posx -= ParentObj.offsetLeft;
				posx += ParentObj.scrollLeft;
				posy -= ParentObj.offsetTop;
				posy += ParentObj.scrollTop;
			}
		}
		posx += document.body.scrollLeft;
		posy += document.body.scrollTop;

//		posx += 10;
		if(MePosX > posx || MePosY > posy || (MePosX + MeWidth) < posx || (MePosY + MeHeight) < posy) {
			MeCloseFlg = true;					//パネル外を触ると消す
			NumKeyBoardHidden();
		}
	}
}

function NumKeyBoardChaseParentScroll(){
	try {
		if(MeObj != null) {
			var sX	= 0;
			var sY	= 0;

			sX					= ParentScrX - ParentObj.scrollLeft;
			sY					= ParentScrY - ParentObj.scrollTop;
			MePosX				= MePosX + sX;
			MePosY				= MePosY + sY;
			MeObj.style.left	= MePosX + "px";
			MeObj.style.top		= MePosY + "px";
			ParentScrX			= ParentObj.scrollLeft;
			ParentScrY			= ParentObj.scrollTop;
		}
	} catch(e) {
	}
}

//カンマ挿入関数
function NumKeyBoardNumberInsertComma(value) {
	var num = new String(value).replace( /,/g, "" );
	while ( num != ( num = num.replace( /^(-?\d+)(\d{3})/, "$1,$2" ) ) );
	return num;
}

